<?php
/**
 * Created by PhpStorm.
 * User: jswei
 * Date: 2018/4/24
 * Time: 8:54
 */

namespace app\first\model;

use app\admin\model\Pic;
use think\Model;

class Member extends Model{
    protected $table = 'think_user';
    protected $pk = 'id';
    protected $auto = ['last_login_ip','update_time'];
    protected $insert = ['sex' => 0];
    protected $autoWriteTimestamp = true;
    protected  static $_field = ['id,account,information,openid,sex,nickname,avatar,hobbies,is_auth,auth_time,
    is_vip,vip_type,is_shop,vip_endtime,access_token,access_token_expire_time'];
    /**Í
     * 获取用户
     * @param $data
     * @return array|null|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getMember($data){
        $info =  is_array($data)?self::field(self::$_field)
            ->where($data)->find():self::field(self::$_field)->find($data);
        if($info){
            $collection = new Collection();
            $subscribe = new Subscribe();
            $info['subscribe'] = $subscribe->where('mid','eq',$data)->count();
            $info['collection'] = $collection->where('mid','eq',$data)->count();
            $info['user_id'] = ($info['id']+1000).(sprintf("%02d",($info['id'] * $info['id'])%100));
//            $info['fans'] = $fans->where('mid','eq',$data)->count();
        }
        return $info;
    }

    /**
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOpenidByMid($id){
        $info = $this->field('id,openid')->find($id);
        return $info['openid'];
    }

    public static function issub($id,$rid){
        $fans = new Fans();
        $info = $fans
            ->where('rid','eq', $id)
            ->where('mid','eq',$rid)
            ->count();
        return $info?1:0;
    }

//    public function getHeadAttr($value){
//        if(empty($value)){
//            return null;
//        }else if(strpos($value,'://')===false){
//            return request()->Domain().DIRECTORY_SEPARATOR.substr($value,1);
//        }else{
//            return $value;
//        }
//    }

    protected function setLastLoginIpAttr(){
        return request()->ip();
    }

    protected function setUpdateTimeAttr(){
        return time();
    }

    protected function setNicknameAttr($value){
        if(empty($value)) return '';
        if(is_special_char($value)){
            return emoji_encode($value);
        }else{
            return $value;
        }
    }

    protected function getNicknameAttr($value){
        if(empty($value)) return '';
        if(is_special_char($value)){
            return emoji_decode($value);
        }else{
            return $value;
        }
    }
}